<template>
  <div class="registerDetail">
    <van-nav-bar
      :fixed="true"
      :placeholder="true"
      :title="$route.meta.title"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 跟踪单详情 -->
    <div class="detail_header flex">
      <div class="detail_header_lt">
        <div class="carNo flex">
          {{ dataSource.carNo }}
          <i class="iconfont icon-right"></i>
        </div>
        <div class="hank">{{ dataSource.customerName }}</div>
      </div>
      <div class="detail_header_rt flex">
        <a class="flex" @click="handleTel(dataSource.mobile1)">
          <i class="iconfont icon-tel"></i>
        </a>
        <div class="iconfont icon-wx" @click.stop="getExList(dataSource)"></div>
      </div>
    </div>
    <!-- 表单 -->
    <div class="formData">
      <van-form ref="form">
        <van-field
          readonly
          clickable
          name="currentDate"
          :value="dataSource.cancelDate"
          input-align="right"
          label="取消日期"
          placeholder="请选择时间"
          @click="handleSelectTime('cancelDate')"
          :rules="[{ required: true }]"
          right-icon="arrow"
        />
        <van-field
          readonly
          clickable
          name="currentDate"
          :value="dataSource.nextBookingDate"
          input-align="right"
          label="下次预约日期"
          placeholder="请选择时间"
          @click="handleSelectTime('nextBookingDate')"
          right-icon="arrow"
          :rules="[{ required: true }]"
        />

        <van-field
          v-model="dataSource.bookingCancel"
          name="备注"
          label="备注"
          type="textarea"
          input-align="left"
          placeholder="请输入取消原因"
          :rules="[{ required: true }]"
          autosize
        />

        <!-- 时间选择弹窗 -->

        <van-popup v-model="showTimerPicker" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            @confirm="onTimeConfirm($event)"
            @cancel="showTimerPicker = false"
            :formatter="formatter"
          />
        </van-popup>

        <div class="submitBtn" @click="formOnSubmit">确认取消</div>
      </van-form>
    </div>
    <van-dialog
      v-model="showDialog"
      title=""
      show-cancel-button
      :showConfirmButton="false"
    >
      <div class="contact_list">
        <div
          class="contact_item flex"
          v-for="(item, index) in contactList"
          :key="index"
        >
          <div class="contact_lt flex">
            <img v-if="item.avatar" class="contact_header" :src="item.avatar" />
            <div class="contact_name">
              {{ item.remark ? item.remark : item.name }}
            </div>
            <div class="contact_com_wx" v-if="item.type == 1">@微信</div>
            <div class="contact_com" v-if="item.type == 2">
              @{{ item.corpName ? item.corpName : item.corpFullName }}
            </div>
          </div>
          <div class="contact_btn" @click="runWxChat(item)">联系</div>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import {
  Search,
  Empty,
  Field,
  Form,
  Uploader,
  DatetimePicker,
  Notify,
  Toast,
  Dialog,
} from 'vant'
import MultipleSelect from '../../components/MultipleSelect/index.vue'
import repairApi from '@/api/repairApi'
import commonApi from '@/api/commonApi'
import { getCookies, isPhone } from '@/utils/util.js'
import axios from 'axios'
import qs from 'qs'
const base_url = process.env.BASE_API
export default {
  name: 'applyRepairEdit',
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    DatetimePicker,
    MultipleSelect,
    Toast,
    Dialog,
    Notify,
  },
  data() {
    return {
      showTimerPicker: false,
      dataSource: {
        billId: '', //单据ID
        cancelDate: '', //取消日期
        nextBookingDate: '', //下次预约日期
        bookingCancel: '', //取消原因
      },
      userId: getCookies('userId'),
      currentDate: new Date(),
      showDialog: false,
      contactList: [],
    }
  },

  mounted() {
    if (localStorage.getItem('applyBillId')) {
      this.dataSource.billId = localStorage.getItem('applyBillId')
      this.getDetail(this.dataSource.billId)
    }
  },
  methods: {
    getDetail(billId) {
      repairApi
        .queryRepairBookingById({
          billId,
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.dataSource = res.data
            // localStorage.setItem('billId', '')
          }
        })
    },

    onTimeConfirm(val) {
      let year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      // let second = val.getSeconds()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      // if (second >= 0 && second <= 9) { second = `0${second}` }
      this.dataSource[this.timeField] = `${year}-${month}-${day}`
      this.showTimerPicker = false
    },

    formatter(type, value) {
      if (type === 'year') {
        this.value1 = value // 可以拿到当前点击的数值
        return `${value}年`
      } else if (type === 'month') {
        this.value2 = value
        return `${value}月`
      }
      this.value3 = value
      return `${value}日`
    },
    // 时间选择
    handleSelectTime(field) {
      this.timeField = field
      this.showTimerPicker = true
    },

    formOnSubmit() {
      this.$refs.form
        .validate()
        .then(() => {
          repairApi
            .cancelRepairBooking({
              ...this.dataSource,
              userId: this.userId,
            })
            .then((res) => {
              console.log(res)
              if (res.code != 0) {
                Notify({ type: 'success', message: '取消成功' })
                this.$router.push('/applyRepair')
              } else {
                Notify({ type: 'danger', message: res.msg })
              }
            })
        })
        .catch(() => {
          this.$toast.fail('请完善信息')
        })
    },
    handleTel(tel) {
      if (isPhone()) {
        window.location.href = `tel:${tel}`
      } else {
        Toast('请在手机端使用此功能')
      }
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    // 获取外部联系人信息
    getExList(data) {
      axios({
        url: `${base_url}/proxy/ext/user/getExList`,
        method: 'post',
        data: qs.stringify(
          // { url: 'http://wycl.autocnd.com:41080/ysc/assessManageDetail' },
          { carNo: data.carNo, name: data.customerName },
          { encode: false },
        ),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          satoken: getCookies('token'),
        },
      }).then((res) => {
        if (res.data && res.data.data && res.data.data.length != 0) {
          this.contactList = res.data.data
          this.showDialog = true
        } else {
          Notify({ type: 'danger', message: '未找到相关联系人' })
        }

        console.log('获取外部联系人信息:', res)
      })
    },
    runWxChat(data) {
      let vm = this
      axios({
        url: `${base_url}/proxy/qywx/jsdkConfig`,
        method: 'post',
        data: qs.stringify(
          // { url: 'http://wycl.autocnd.com:41080/ysc/assessManageDetail' },
          { url: location.href.split('?')[0], type: 'app' },
          { encode: false },
        ),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          satoken: getCookies('token'),
        },
      }).then((res) => {
        console.log('jsdkConfig:', res)
        let jsdk = res.data.data
        localStorage.setItem('jsdk', JSON.stringify(res.data.data))
        wx.agentConfig({
          corpid: jsdk.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
          agentid: jsdk.agentid, // 必填，企业微信的应用id （e.g. 1000247）
          timestamp: jsdk.timestamp, // 必填，生成签名的时间戳
          nonceStr: jsdk.nonceStr, // 必填，生成签名的随机串
          signature: jsdk.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
          jsApiList: ['openEnterpriseChat'], //必填，传入需要使用的接口名称
          success: function (res) {
            console.log('agentConfig权限成功返回信息:', res)
            wx.openEnterpriseChat({
              // 注意：userIds和externalUserIds至少选填一个。内部群最多2000人；外部群最多500人；如果有微信联系人，最多40人
              userIds: '', //参与会话的企业成员列表，格式为userid1;userid2;...，用分号隔开。
              externalUserIds: data.externalUserid, // 参与会话的外部联系人列表，格式为userId1;userId2;…，用分号隔开。
              groupName: '', // 会话名称。单聊时该参数传入空字符串""即可。
              chatId: '', // 若要打开已有会话，需指定此参数。如果是新建会话，chatId必须为空串
              success: function (res) {
                var chatId = res.chatId //返回当前群聊ID，仅当使用agentConfig注入该接口权限时才返回chatId
                // 回调
              },
              fail: function (res) {
                if (res.errMsg.indexOf('function not exist') > -1) {
                  alert('版本过低请升级')
                }
              },
            })
          },
          fail: function (res) {
            console.log('agentConfig权限失败返回信息:', res)
            if (res.errMsg.indexOf('function not exist') > -1) {
              alert('版本过低请升级')
            }
          },
        })
      })
    },
  },
}
</script>

<style lang="less" scoped>
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  background: #f3f3f3;
  .detail_header {
    justify-content: space-between;
    margin: 0.2rem 0.2rem;
    border-radius: 5px;
    background: #fff;
    padding: 0.3rem;
    .detail_header_lt {
      .carNo {
        font-size: 0.32rem;
        font-weight: bold;
        margin-bottom: 0.2rem;
        .icon-right {
          margin-left: 0.2rem;
          color: #409eff;
        }
      }
      .hank {
        font-size: 0.28rem;
        color: #666;
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 0.28rem;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 0.32rem;
        padding: 0.1rem;
        border-radius: 50%;
        margin-right: 0.1rem;
      }
      .icon-wx {
        color: #409eff;
        font-size: 0.65rem;
      }
    }
  }
  .formData {
    background: #fff;
    padding-bottom: 0.5rem;
  }
}
/deep/.van-field__error-message {
  text-align: right;
}
.submitBtn {
  background: #409eff;
  color: #fff;
  width: 75%;
  margin: auto;
  text-align: center;
  padding: 0.25rem;
  border-radius: 5px;
  margin-top: 0.6rem;
  font-size: 0.3rem;
}
.contact_list {
  padding: 0.5rem 0.2rem 0 0.2rem;
  .contact_item {
    justify-content: space-between;
    margin-bottom: 20px;
  }
  .contact_lt {
    font-size: 0.28rem;
    color: #23ec1c;
    .contact_header {
      width: 30px;
      height: 30px;
      display: block;
      border-radius: 5px;
      margin-right: 5px;
    }

    .contact_name {
      font-size: 0.28rem;
      color: #333;
      margin-left: 5px;
    }
    .contact_com {
      color: #f65e07;
      font-size: 0.28rem;
    }
    .contact_com_wx {
      color: #23ec1c;
      font-size: 0.28rem;
    }
  }
  .contact_btn {
    background: #409eff;
    color: #fff;
    padding: 5px 15px;
    border-radius: 3px;
    font-size: 0.28rem;
  }
}
</style>
